import { AxiosResponse } from 'axios'
import { BookInfo } from './state'
import { defineStore } from 'pinia'
import goodStorage from 'good-storage'
import BookApi from '@/api/BookApi'
import { hasArrProps } from '@/utils/objectUtil'
import { procDecimalZero } from '@/utils/numberUtil'

// 图书相关store
export default defineStore('bookstore', {
  state: () => {
    return {
      bookList: [] as BookInfo[], // 图书列表
    }
  },
  getters: {
    // 获取图书列表
    getBookList(state): BookInfo[] {
      return hasArrProps(state.bookList) ? this.bookList : goodStorage.get('bookList') // pinia 的 state 有值就从 state 中取否则从 Local Storage 中取
    }
  },
  actions: {
    // 根据图书3级分类id保存查询对应图书信息
    // sortField 排序字段
    // ascOrDesc 排序规则
    async findBooksByThirdCtgyId(thirdCtgyid: number, sortField: string, ascOrDesc: string) {
      const bookList: AxiosResponse<BookInfo[]> = await BookApi.getBookList(thirdCtgyid, sortField, ascOrDesc)

      bookList.data = bookList.data.map(book => {
        book.discountprice = procDecimalZero(book.originalprice * book.discount) // 获取折扣价
        return book
      })
      this.bookList = bookList.data
      goodStorage.set('bookList', this.bookList) // 将图书列表缓存到 Local Storage 中
    }
  }
})

// 小数变整数
const toFixed_ = (num: number): number => {
  return Math.trunc(num)
}

